package cn.fancy.sdk.common.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

import android.util.Base64;
import android.util.Log;

public class SE {
	private static final String key = "qdazzlenativesdk";

	private SecretKeySpec skeySpec;
	private Cipher encrypt;
	private Cipher decrypt;

	private SE() {
		init();
	}

	private static class SEHolder {
		private static SE instance = new SE();
	}

	public static SE getInstance() {
		return SEHolder.instance;
	}

	private void init() {

		try {
			byte[] raw = key.getBytes("ASCII");
			skeySpec = new SecretKeySpec(raw, "AES");

			encrypt = Cipher.getInstance("AES");
			encrypt.init(Cipher.ENCRYPT_MODE, skeySpec);

			decrypt = Cipher.getInstance("AES");
			decrypt.init(Cipher.DECRYPT_MODE, skeySpec);
		} catch (Exception e) {
			Log.d("init() - ", e.getLocalizedMessage());
		}
	}

	public byte[] encrypt(byte[] plain_bytes) {

		if (plain_bytes == null || plain_bytes.length <= 0)
			return null;

		byte[] encrypted_bytes = null;
		try {
			encrypted_bytes = encrypt.doFinal(plain_bytes);
		} catch (Exception e) {
			Log.d("SE.encrypt(...)", e.getLocalizedMessage());
		}

		return encrypted_bytes;
	}

	public byte[] decrypt(byte[] encrypted_bytes, int offset, int len) {

		if (encrypted_bytes == null || len <= 0)
			return null;

		byte[] plain_bytes = null;
		try {
			plain_bytes = decrypt.doFinal(encrypted_bytes, offset, len);
		} catch (Exception e) {
			Log.d("SE.decrypt(...)", e.getLocalizedMessage());
		}

		return plain_bytes;
	}

	public static String DO_ENCRYPT_BASE64(String content) {

		if (content == null)
			return "";

		try {
			byte[] plain_bytes = content.getBytes("utf-8");
			byte[] encrypted_bytes = SE.getInstance().encrypt(plain_bytes);
			String str = Base64.encodeToString(encrypted_bytes, Base64.DEFAULT);
			return str;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	public static String DO_DECRYPT_BASE64(String content) {

		if (content == null)
			return "";

		try {
			byte[] encrypted_bytes = Base64.decode(content, Base64.DEFAULT);
			byte[] plain_bytes = SE.getInstance().decrypt(encrypted_bytes, 0,
					encrypted_bytes.length);

			return new String(plain_bytes, "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}

}
